package com.dfdchem.imd.kaiwu.manager;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.view.View;
import android.widget.ImageView;

import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentActivity;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.RequestManager;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.RequestOptions;
import com.bumptech.glide.request.target.CustomTarget;
import com.bumptech.glide.request.transition.Transition;
import com.dfdchem.imd.kaiwu.application.KWApp;
import com.dfdchem.imd.kaiwu.interfaces.GlideDownloadListener;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.RequestUtil;
import com.dfdchem.imd.kaiwu.util.StringUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

/**
 * @date 2020年8月3日
 * @author yqq
 * 统一的Glide加载管理类
 */
public class GlideManager {

    private static final String TAG = "GlideManager";

    // 用来控制生命周期跟随
    private RequestManager requestManager;

    private Object attachObject = null;

    public GlideManager(Context context) {
        this.requestManager = Glide.with(context);
        attachObject = context;
    }

    public GlideManager(Activity activity) {
        this.requestManager = Glide.with(activity);
        attachObject = activity;
    }

    public GlideManager(View view) {
        this.requestManager = Glide.with(view);
        attachObject = view;
    }

    public GlideManager(Fragment fragment) {
        this.requestManager = Glide.with(fragment);
        attachObject = fragment;
    }

    public GlideManager(FragmentActivity fragmentActivity) {
        this.requestManager = Glide.with(fragmentActivity);
        attachObject = fragmentActivity;
    }

    //判断Activity是否Destroy
    private static boolean isDestroy(Activity activity) {
        if (activity == null || activity.isFinishing() || activity.isDestroyed()) {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 处理图片短链接的问题
     * @param oldUrl
     * @return
     */
    private String urlConvert(String oldUrl) {
        String newUrl = null;

        // 1、处理图片短链接
        if (oldUrl.startsWith("/Fe/Files/Index")) {
            oldUrl = RequestUtil.URL_BASE_API + oldUrl;
        }

        newUrl = IntranetManager.convert(oldUrl);

        Log.d(TAG, oldUrl + " => " + newUrl);
        return newUrl;
    }

    public void load(ImageView view, String url) {
        this.load(view, url, null, null);
    }

    public void load(ImageView view, String url, RequestOptions options) {
        this.load(view, url, options, null);
    }

    @SuppressLint("CheckResult")
    public void load(ImageView view, String url, RequestOptions options, RequestListener<android.graphics.drawable.Drawable> listener) {

        if (StringUtil.isEmpty(url)) {
            return;
        }

        url = urlConvert(url);

        RequestBuilder<android.graphics.drawable.Drawable> requestBuilder = requestManager.load(url);
        if (options != null) {
            requestBuilder.apply(options);
        }

        if (listener != null) {
            requestBuilder.addListener(listener);
        }

        if (attachObject == null) {
            return;
        }

        if (attachObject instanceof Activity) {
            Activity activity = (Activity) attachObject;
            if (isDestroy(activity)) {
                return;
            }
        } else if (attachObject instanceof Fragment) {
            Fragment fragment = (Fragment) attachObject;
            if (!fragment.isAdded()) {
                return;
            }
        }

        requestBuilder.into(view);
    }

    public void load(ImageView view, File file) {
        this.load(view, file, null, null);
    }

    @SuppressLint("CheckResult")
    public void load(ImageView view, File file, RequestOptions options, RequestListener<android.graphics.drawable.Drawable> listener) {

        if (!file.exists()) {
            return;
        }

        RequestBuilder<android.graphics.drawable.Drawable> requestBuilder = requestManager.load(file);
        if (options != null) {
            requestBuilder.apply(options);
        }

        if (listener != null) {
            requestBuilder.addListener(listener);
        }

        requestBuilder.into(view);
    }

    public void save(String url, final GlideDownloadListener listener) {
        url = urlConvert(url);
        requestManager.asBitmap().load(url).into(new CustomTarget<Bitmap>() {
            @Override
            public void onResourceReady(Bitmap bitmap, Transition<? super Bitmap> transition) {
                try {
                    File cacheDir = KWApp.getInstance().getExternalCacheDir();
                    if (cacheDir != null && !cacheDir.exists()) {
                        cacheDir.mkdirs();
                    }

                    String fileUri = cacheDir.getAbsolutePath() + File.separator + System.currentTimeMillis() + ".png";
                    FileOutputStream outputStream = new FileOutputStream(fileUri);

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
                    outputStream.flush();
                    outputStream.close();

                    if (listener != null ){
                        listener.onDownloadSuccess(fileUri);
                    }
                } catch(IOException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onLoadCleared(Drawable placeholder) {
            }
        });
    }
}
